using UnityEngine;

namespace BuildingSystem.Scripts
{
    public class BuildingsPlacer : MonoBehaviour
    {
        private Camera _mainCamera;
        private PlayerInput _playerInput;

        [SerializeField] private BuildingsGrid _buildingsGrid;

        private Building _selectedBuilding;
        private bool _canPlaceSelectedBuilding;

        private void Awake()
        {
            _mainCamera = Camera.main;
            _playerInput = FindObjectOfType<PlayerInput>();
        }

        private void Start() 
        {
            _playerInput.OnMouseMoved += MouseMoved;
            _playerInput.OnLeftMouseButtonClicked += PlaceSelectedBuilding;
            _playerInput.OnRightMouseButtonClicked += RotateSelectedBuilding;
            _playerInput.OnEscapePressed += DestroySelectedBuilding;
        }

        private void MouseMoved()
        {   
            if (_selectedBuilding == null)
                return;

            var ray = _mainCamera.ScreenPointToRay(_playerInput.MousePosition);
            if (_buildingsGrid.GridPlane.Raycast(ray, out var distance))
            {
                var worldPoint = ray.GetPoint(distance);
                var gridPoint = _buildingsGrid.WorldToGridPoint(worldPoint);

                var position = new Vector3(gridPoint.x, 0, gridPoint.y);
                _selectedBuilding.transform.position = position;

                _canPlaceSelectedBuilding = _buildingsGrid.CanSet(_selectedBuilding);
            }
        }

        private void PlaceSelectedBuilding()
        {
            if (_selectedBuilding != null && _canPlaceSelectedBuilding)
            {
                _buildingsGrid.Set(_selectedBuilding);
                _selectedBuilding = null;
            }
        }

        private void RotateSelectedBuilding()
        {
            if (_selectedBuilding != null)
                _selectedBuilding.Rotate();
            
        }

        private void DestroySelectedBuilding()
        {
            if (_selectedBuilding != null)
                Destroy(_selectedBuilding.gameObject);
        }

        public void SetSelectedBuilding(Building building)
        {
            if (_selectedBuilding != null)
                DestroySelectedBuilding();

            _selectedBuilding = Instantiate(
                building,
                _playerInput.MousePosition,
                Quaternion.identity,
                transform);
        }
    }
}